package org.jackysoft.util;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.Predicate;

import com.google.common.collect.Lists;

public class CollectionUtils extends
		org.apache.commons.collections.CollectionUtils {
	public static void notNullable(Collection<?> col) {
		if (col == null)
			return;
		org.apache.commons.collections.CollectionUtils.filter(col,
				new Predicate() {

					@Override
					public boolean evaluate(Object object) {
						// TODO Auto-generated method stub
						return object != null;
					}

				});
	}
	

	public static Iterable<Object> iterablize(final Iterator<Object> itr) {
		return new Iterable<Object>() {

			@Override
			public Iterator<Object> iterator() {
				return itr;
			}

		};
	}

	/**
	 * 从一个list里查找一个数据项
	 * 
	 * @param dataSets
	 *            数据项集合
	 * @param example
	 *            数据项特征样例
	 * @return null 如果没有找到
	 * */
	public static <T extends Comparable<T>> T findByCode(
			Collection<T> dataSets, T example) {
		if (CollectionUtils.isEmpty(dataSets))
			return null;
		T tmp = null;
		List<T> ls = Lists.newArrayList();
		ls.addAll(dataSets);
		Collections.sort(ls);
		int idx = Collections.binarySearch(ls, example);

		if (idx >= 0) {// 找到
			tmp = ls.get(idx);
		} else {
			tmp = null;
		}
		return tmp;
	}

	/**
	 * 从一个list里查找一个数据项
	 * 
	 * @param dataSets
	 *            数据项集合
	 * @param example
	 *            数据项特征样例
	 * @return null 如果没有找到
	 * */
	public static <T extends Comparable<T>> T find(Collection<T> dataSets,
			T example) {
		if (CollectionUtils.isEmpty(dataSets))
			return null;
		T tmp = null;
		List<T> ls = Lists.newArrayList();
		ls.addAll(dataSets);
		Collections.sort(ls);
		int idx = Collections.binarySearch(ls, example);
		if (idx >= 0) {// 找到
			tmp = ls.get(idx);
		} else {
			tmp = null;
		}
		return tmp;
	}

	public static <T extends Comparable<T>> T find(Collection<T> dataSets,
			T example, Comparator<T> cond) {
		if (CollectionUtils.isEmpty(dataSets))
			return null;
		T tmp = null;
		List<T> ls = Lists.newArrayList();
		ls.addAll(dataSets);
		Collections.sort(ls);
		int idx = Collections.binarySearch(ls, example, cond);

		if (idx >= 0) {// 找到
			tmp = ls.get(idx);
		} else {
			tmp = null;
		}
		return tmp;
	}
}
